$(document).ready(function() {

    if (document.body.clientWidth < 1290) {
        $('#pageContent').css('width', '1000px');
        $('#pageContent').css('overflow', 'auto');
    }

    $('#ajaxBlock .pages a').live("click", function(e) {
        e.preventDefault();
        $.blockUI();
        $('#dialog').load($(this).attr('href'), function() {
            $.unblockUI();
        });
    });
    $('.filter-clear').live("click", function(e) {
        var form = $(this).parents().children('.filter-container').filter(':first').find('form').filter(':first');
        form[0].reset();
    });


    // filter
    $('.filter-lnk').live("click", function(e) {
        $(this).parents().children('.filter-container').filter(':first').slideToggle('slow');
        $(this).toggleClass("filter-lnk-active");
    });
    $('.filter-close').live("click", function(e) {
        $(this).parents().children('.filter-container').filter(':first').slideUp('slow');
        $(this).parents().children('.filter-lnk').filter(':first').removeClass("filter-lnk-active");
    });

    $('.info-table .orderByLink').live("click", function(e) {
        e.preventDefault();
        var field = $(this).attr('data-order-fld');
        var dir = $(this).attr('data-order-dir');
        var str = '';
        var obj = $('#filterForm');

        $(obj).find('.send-val').each(function(index, el) {
            if (el.value) {
                str += el.name + '/' + el.value + '/';
            }
        });
        str += 'order_field/' + field + '/order_dir/' + dir + '/'
        var action = $(obj).attr('action');
        $.blockUI();
        $.post(action + str, '', function(data) {
            $('#pageContent').html(data);
            $.unblockUI();
        });
    });
});

function getAction(str) {

    var info = str.split('|');
    var temp = info[0].split('*');
    var controller = (temp[1]) ? temp[1] : moduleName;
    var action = temp[0];
    var id = info[1];
    var event = info[2];
    var title = info[3];
    var widthW = parseInt(info[info.length - 1]);
    if (!widthW || widthW < 200)
        widthW = 500;

    $.blockUI();
    $.post('/admin/' + controller + '/' + action + '/?' + ((id) ? 'id=' + id + '&' : '') + ((event) ? 'event=' + event : ''), function(data) {
        if (data == -1) {
            data = 'No data!';
        }
        $('#dialog').html(data);
        $.unblockUI();
        $('#dialog').dialog({
            title: title,
            modal: true,
            width: widthW,
            buttons: {
                "OK": function() {
                    var obj = $('#infoForm');
                    if (checkform(obj)) {
                        var str = $(obj).serialize();
                        $.blockUI();
                        $.post(redirectUrl, str, function(data) {
                            if (data != false) {
                                $('#pageContent').html(data);
                                $('#dialog').dialog('close');
                                globalModule.alertMessages();
                            } else {
                                $('#dialog').dialog('close');
                            }
                            $.unblockUI();
                        });
                    }
                    ;
                },
                "Cancel": function() {
                    $('#dialog').dialog('close');
                }
            }
        });
    });
}

function page() {

    this.getPageInfo = function(page_id, controller_name) {
        if (page_id) {
            var sControllerName = controller_name || 'pages';
            $.blockUI();
            $.post('/admin/' + sControllerName + '/get-page-info/', {
                page_id: page_id
            }, function(data) {
                $("#labels option").prop("selected", false);
                for (var i = 0, len = data.labels.length; i < len; i++) {
                    var item = data.labels[i];
                    $("#labels [value='" + item + "']").prop("selected", true);
                }
                $('#ckeditorBlock').show('slow');

                $($('#infoForm')).find('.send-val').each(function(index, el) {
                    el.value = data[el.name];
                });
                CKEDITOR.instances.ckeditor.setMode('source');
                CKEDITOR.instances.ckeditor.setData(data.content);
                $('#top_menu').prop('checked', (data.top_menu == 1) ? true : false);
                $('#active').prop('checked', (data.active == 1) ? true : false);
                $('#in_main').prop('checked', (data.in_main == 1) ? true : false);
                $('#is_comment').prop('checked', (data.is_comment == 1) ? true : false);
                $("#category_id [value='" + data.category_id + "']").attr("selected", "selected");

                $('#event').val('updatePage');
                $('#id').val(data.id);
                $.unblockUI();
            }, 'json');
        }
    }

    this.savePage = function() {

        if (checkform($('#infoForm'))) {
            var dataSend = {};
            $($('#infoForm')).find('.send-val-multi').each(function(index, el) {
                if ($(this).val())
                    dataSend[el.name] = $(this).val().join('|');
            });
            $($('#infoForm')).find('.send-val').each(function(index, el) {
                dataSend[el.name] = el.value;
            });
            dataSend.content = CKEDITOR.instances.ckeditor.getData();
            dataSend.active = ($('#active').attr('checked')) ? 1 : 0;
            dataSend.in_main = ($('#in_main').attr('checked')) ? 1 : 0;
            dataSend.top_menu = ($('#top_menu').attr('checked')) ? 1 : 0;
            dataSend.is_comment = ($('#is_comment').attr('checked')) ? 1 : 0;
            $.blockUI();
            $.post(redirectUrl, { dataSend: dataSend, event: dataSend.event }, function(data) {
                if (data != false) {
                    $('#pageContent').html(data);
                    $('#ckeditorBlock').hide('slow');
                }
                $.unblockUI();
            });

        }

    }
    
    this.saveShortStories = function() {
        if (checkform($('#infoForm'))) {
            var dataSend = {};
            $($('#infoForm')).find('.send-val-multi').each(function(index, el) {
                if ($(this).val())
                    dataSend[el.name] = $(this).val().join('|');
            });
            $($('#infoForm')).find('.send-val').each(function(index, el) {
                dataSend[el.name] = el.value;
            });
            dataSend.content = CKEDITOR.instances.ckeditor.getData();
            dataSend.active = ($('#active').attr('checked')) ? 1 : 0;
            $.blockUI();
            $.post(redirectUrl, dataSend, function(data) {
                if (data != false) {
                    $('#pageContent').html(data);
                    $('#ckeditorBlock').hide('slow');
                }
                $.unblockUI();
            });

        }

    }

    this.createPage = function() {
        $('#ckeditorBlock').show('slow');
        var form = $('#infoForm');
        form[0].reset();
        $('#event').val('createPage');
        $('#id').val('');
        $('#active').prop('checked', true);
        CKEDITOR.instances.ckeditor.setData('');
    }

}

function globalModule() {

    this.alertMessages = function() {
        if ($('#messageBox').length) {
            $('#dialog').html($('#messageBox').html());
            $('#messageBox').remove();
            $('#dialog').dialog({
                title: 'Information',
                modal: true,
                width: 300,
                buttons: {
                    "OK": function() {
                        $('#dialog').dialog('close');
                    }
                }
            });
        }

    }

    this.deleteRow = function(id) {

        $('#dialog').html(messageRemoveRow);
        $('#dialog').dialog({
            title: 'Remove',
            modal: true,
            width: 250,
            buttons: [
                {
                    text: "OK",
                    click: function() {
                        //alert(redirectUrl+'?event=removeRow&id='+id); return;
                        $('#dialog').dialog('close');
                        $.blockUI();
                        $.post(redirectUrl + '?event=removeRow&id=' + id, function(data) {
                            if (data != false) {
                                $('#pageContent').html(data);
                                globalModule.alertMessages();
                            }
                            $.unblockUI();
                        });
                    }
                },
                {
                    text: "Cancel",
                    click: function() {
                        $('#dialog').dialog('close');
                    }
                }

            ]
        });
        return false;
    }

}
var globalModule = new globalModule();
var page = new page;

function prepareURL(obj) {
    var numPage = parseInt($(obj).val());
    if (!isThisInt(numPage)) {
        alertUI('Value must be an integer', obj);
    } else {
        var maxPage = $(obj).attr('max')
        if (maxPage && numPage > maxPage)
            numPage = maxPage;
        var url = $(obj).attr('rel').replace('replaceThisValue', numPage);
        window.location = url;
    }

}

function sendQuery(obj) {
    if (checkform(obj)) {
        var str = '';
        $(obj).find('.send-val').each(function(index, el) {
            if (el.value) {
                str += el.name + '/' + el.value + '/';
            }
        });
        $(obj).find('.send-val-multi').each(function(index, el) {
            if (el.value) {
                str += el.name.replace('[]', '') + '/' + $(this).val().join('|') + '/';
            }
        });
        //   if(str){
        var action = $(obj).attr('action');
        //console.log(action+str); return false;
        $.blockUI();
        $.post(action + str, '', function(data) {
            $('#pageContent').html(data);
            $.unblockUI();
        });
        //    }
    }
    return false;
}

function checkform(obj) {
    var validation = $(obj).find(".valid");
    var error = false;
    if (validation) {
        validation.removeClass('error-ico');
        validation.each(function(index, el) {
            if ($(this).hasClass('email')) {
                validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
                strEmail = el.value;
                if (strEmail.search(validRegExp) == -1) {
                    error = true;
                    $(this).addClass('error-ico');
                }
            }
            else {
                if (!trim(el.value)) {
                    error = true;
                    $(this).addClass('error-ico');
                }
            }
        });
    }

    var validation = $(obj).find(".thisInt");
    if (validation) {
        validation.each(function(index, el) {
            if (el.value) {
                if (!isThisInt(el.value)) {
                    error = true;
                    $(this).addClass('error-ico');
                }
            }
        });
    }

    var validation = $(obj).find(".no-zero");
    if (validation) {
        validation.each(function(index, el) {
            if (el.value) {
                if (!isThisInt(el.value) || el.value < 1) {
                    error = true;
                    $(this).addClass('error-ico');
                }
            }
        });
    }
    if (!error) {
        var addCheck = $(obj).attr('rel');
        if (addCheck) {
            return eval(addCheck + '(obj);');
        } else {
            return true;
        }
    } else {
        return false;
    }
}

function in_array(value, array)
{
    for (var i = 0; i < array.length; i++)
    {
        if (array[i] == value)
            return true;
    }
    return false;
}

function isThisInt(number) {
    return (!isNaN(number * 1))
}

function alertUI(message, sFocus, width) {
    if (message) {
        var width = width || 350;
        $('#dialog1').html(message);
        $('#dialog1').dialog({
            title: $('#title_inf').html(),
            modal: true,
            width: width,
            buttons: {
                "OK": function() {
                    $('#dialog1').dialog('close');
                    if (sFocus)
                        $(sFocus).val('').addClass('error-ico').focus();
                }
            }
        });
    }
}


function trim(string) {
    if (!string)
        return;
    return string.replace(/(^\s+)|(\s+$)/g, string);
}

function dialogUI(obj, widthW) {
    $.unblockUI();
    $('#dialog').dialog({
        title: 'Information',
        modal: true,
        width: widthW,
        buttons: {
            "OK": function() {
                var obj = $('#infoForm');
                if (checkform(obj)) {
                    var str = $(obj).serialize();
                    $.blockUI();
                    $.post(redirectUrl, str, function(data) {
                        if (data != false) {
                            $('#pageContent').html(data);
                            //  $('#dialog').dialog('close');
                            globalModule.alertMessages();
                        } else {
                            $('#dialog').dialog('close');
                        }
                        $.unblockUI();
                    });
                }
                ;
            },
            "Cancel": function() {
                $('#dialog').dialog('close');
            }
        }
    });
}

function dialogUINoButton(widthW) {
    $.unblockUI();
    $('#dialog').dialog({
        title: 'Information',
        modal: true,
        width: widthW
    });
}

function dialogUIwithNoOkButton(widthW) {
    $.unblockUI();
    $('#dialog').dialog({
        title: 'Information',
        modal: true,
        width: widthW,
        buttons: {
            "Cancel": function() {
                $.unblockUI();
                $('#dialog').dialog('close');
            }
        }
    });
}
function dialogUIOkButton(widthW) {
    $.unblockUI();
    $('#dialog').dialog({
        title: 'Information',
        modal: true,
        width: widthW,
        buttons: {
            "OK": function() {
                $.unblockUI();
                $('#dialog').dialog('close');
            }
        }
    });
}

function dialogOk(html, widthW) {
    $('#dialog').html(html);
    $('#dialog').dialog({
        title: 'Information',
        modal: true,
        width: widthW,
        buttons: {
            "OK": function() {
                $('#dialog').dialog('close');
            }
        }
    });
}

function multiReplace(pat, to, rs) {
    var fnd = 0;
    while (fnd >= 0) {
        rs = rs.replace(pat, to);
        fnd = rs.lastIndexOf(pat);
    }
    return rs;
}